const Router = require('@koa/router')
const router = new Router()
const { sign, verify, refreshVerify } = require('../utils/jwt.js')
const { escape } = require('../utils/security.js')
const getConnection = require('../config/connection')

router.prefix('/user')

// 登录
router.post('/login', async (ctx) => {
    let { username, password } = ctx.request.body
    username = escape(username)
    password = escape(password)
    
    const conn = await getConnection()
    try {
        // 查用户
        const [rows] = await conn.execute(
            'SELECT * FROM users WHERE username = ? AND password = ?',
            [username, password]
        )

        if (rows.length) {
            const user = rows[0]

            // 查用户对应的 plan
            const [plans] = await conn.execute(
                'SELECT * FROM plan WHERE user_id = ?',
                [user.id]
            )

            // 查用户对应的 data
            const [dataRows] = await conn.execute(
                'SELECT * FROM data WHERE user_id = ?',
                [user.id]
            )
            const userData = dataRows[0] || {}

            // 直接使用数据（mysql2已经自动解析了JSON字段）
            const dataResponse = {
                monthly_sports: userData.monthly_sports || new Array(31).fill(0),
                today_training: userData.today_training || {
                    "有氧运动": 0,
                    "瑜伽": 0,
                    "休息": 0,
                    "力量训练": 0
                },
                weekly_calories: userData.weekly_calories || new Array(7).fill(0),
                update_time: userData.update_time || Date.now()
            }

            // // 调试输出，确认数据结构
            // console.log('monthly_sports:', typeof dataResponse.monthly_sports, dataResponse.monthly_sports)
            // console.log('today_training:', typeof dataResponse.today_training, dataResponse.today_training)
            // console.log('weekly_calories:', typeof dataResponse.weekly_calories, dataResponse.weekly_calories)

            // 返回完整数据
            ctx.body = {
                code: '1',
                msg: '登录成功',
                data: {
                    user,
                    plans,
                    data: dataResponse
                },
                access_token: sign({ id: user.id, username: user.username, nickname: user.nickname }, '1h'),
                refresh_token: sign({ id: user.id, username: user.username, nickname: user.nickname }, '7d')
            }
        } else {
            ctx.body = { code: '0', msg: '账号或密码错误', data: {} }
        }
    } catch (err) {
        console.error('登录异常:', err)
        ctx.body = { code: '-1', msg: '服务器异常', data: err.message }
    } finally {
        await conn.end()
    }
})

// 注册
router.post('/register', async (ctx) => {
    let { username, password, nickname } = ctx.request.body
    if (!username || !password || !nickname) {
        ctx.body = { code: '0', msg: '账号、密码、昵称不能为空', data: {} }
        return
    }

    username = escape(username)
    password = escape(password)
    nickname = escape(nickname)

    const conn = await getConnection()
    try {
        // 检查是否已存在用户
        const [exist] = await conn.execute('SELECT * FROM users WHERE username = ?', [username])
        if (exist.length) {
            ctx.body = { code: '0', msg: '账号已存在', data: {} }
            return
        }

        await conn.beginTransaction()

        // 插入 users 表
        const [userResult] = await conn.execute(
            'INSERT INTO users (username, password, nickname, create_time) VALUES (?, ?, ?, ?)',
            [username, password, nickname, Date.now()]
        )
        const userId = userResult.insertId
        console.log('注册用户ID:', userId) // 打印调试

        // 插入 plan 表，关联用户
        await conn.execute(
            'INSERT INTO plan (create_time, user_id) VALUES (?, ?)',
            [Date.now(), userId]
        )

        // 插入 data 表 - 使用JSON.stringify
        const monthlySports = JSON.stringify(new Array(31).fill(0));
        const todayTraining = JSON.stringify({
            "有氧运动": 0,
            "瑜伽": 0,
            "休息": 0,
            "力量训练": 0
        });
        const weeklyCalories = JSON.stringify(new Array(7).fill(0));

        await conn.execute(
            `INSERT INTO data (user_id, monthly_sports, today_training, weekly_calories, update_time) 
             VALUES (?, ?, ?, ?, ?)`,
            [userId, monthlySports, todayTraining, weeklyCalories, Date.now()]
        )

        await conn.commit()
        ctx.body = { code: '1', msg: '注册成功', data: { userId } }

    } catch (err) {
        await conn.rollback()
        console.error('注册失败:', err)
        ctx.body = { code: '-1', msg: '注册失败', data: err.message }
    } finally {
        await conn.end()
    }
})

// 刷新 token
router.post('/refresh', (ctx) => {
    const { refresh_token } = ctx.request.body
    const decoded = refreshVerify(refresh_token)
    if (decoded && decoded.id) {
        const data = { id: decoded.id, username: decoded.username, nickname: decoded.nickname }
        ctx.body = { code: '1', msg: 'token刷新成功', access_token: sign(data, '1h'), refresh_token: sign(data, '7d') }
    } else {
        ctx.status = 416
        ctx.body = { code: '0', msg: '登录失效' }
    }
})

// 获取用户信息
router.get('/profile', verify(), async (ctx) => {
    const conn = await getConnection()
    try {
        const [rows] = await conn.execute(
            'SELECT id, username, nickname, sex, age, height, weight FROM users WHERE id = ?',
            [ctx.userId]
        )
        ctx.body = { code: '1', data: rows[0] || {} }
    } catch (err) {
        ctx.body = { code: '-1', msg: '获取用户信息失败', data: err.message }
    } finally {
        await conn.end()
    }
})

module.exports = router
